package com.zhentao.controller;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/es")
public class EsController {
    private RestHighLevelClient esClient;

    @PostConstruct
    public void init() {
        esClient = new RestHighLevelClient(
                RestClient.builder(new org.apache.http.HttpHost("192.168.119.128", 9200, "http"))
        );
    }

    @PreDestroy
    public void close() throws IOException {
        if (esClient != null) esClient.close();
    }

    // 增加/更新
    @PostMapping("/add")
    public String addOrUpdate(@RequestBody Map<String, Object> doc) throws IOException {
        IndexRequest request = new IndexRequest("zt_test1")
                .id(doc.get("id").toString())
                .source(doc, XContentType.JSON);
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        return response.getResult().name();
    }

    // 查询
//    @GetMapping("/get/{id}")
//    public Map<String, Object> get(@PathVariable String id) throws IOException {
//        GetRequest getRequest = new GetRequest("zt_test1", id);
//        GetResponse getResponse = esClient.get(getRequest, RequestOptions.DEFAULT);
//        return getResponse.getSource();
//    }

    // 删除
    @DeleteMapping("/delete/{id}")
    public String delete(@PathVariable String id) throws IOException {
        esClient.delete(new DeleteRequest("zt_test1", id), RequestOptions.DEFAULT);
        return "deleted";
    }

    // 查询所有
    @GetMapping("/list")
    public Object list() throws IOException {
        SearchRequest searchRequest = new SearchRequest("zt_test1");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(sourceBuilder);
        return esClient.search(searchRequest, RequestOptions.DEFAULT);
    }

//    数据导入
    @PostMapping("/import")
    public String importFromMysql() throws Exception {
        try (Connection conn = DriverManager.getConnection(
                "jdbc:mysql://192.168.119.128:3306/test?useSSL=false&serverTimezone=UTC",
                "root", "ztjymysql");
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT id, Path, Title FROM minio")) {
            int count = 0;
            while (rs.next()) {
                Map<String, Object> jsonMap = new HashMap<>();
                jsonMap.put("id", rs.getInt("id"));
                jsonMap.put("Name", rs.getString("Title"));
                jsonMap.put("sex", "");
                jsonMap.put("age", 0);
                IndexRequest request = new IndexRequest("zt_test1")
                        .id(String.valueOf(rs.getInt("id")))
                        .source(jsonMap, XContentType.JSON);
                esClient.index(request, RequestOptions.DEFAULT);
                count++;
            }
            return "成功导入了 " + count + "条数据从MySQL到ES";
        }
    }
} 